package com.itheima.service.impl;

import com.itheima.mapper.GoodsMapper;
import com.itheima.pojo.Goods;
import com.itheima.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Override
    public List<Goods> find() {
        List<Goods> list = goodsMapper.find();
        List<Goods> parent = list.stream().filter(p -> p.getParentId() == 0).toList();
        List<Goods> children = list.stream().filter(c -> c.getParentId() > 0).toList();
        parent.forEach(p->getChildren(p,children));
        return parent;
    }

    private void getChildren(Goods currentGoods, List<Goods> children) {
        List<Goods> goodsList = children.stream().filter(p -> Objects.equals(currentGoods.getId(), p.getParentId())).toList();
        goodsList.forEach(g->getChildren(g,children));
        currentGoods.setChildren(goodsList);
    }
}
